package org.example.back.controller.user;

import jakarta.servlet.http.HttpSession;
import org.example.back.entity.user.UserPlan;
import org.example.back.service.user.UserPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.time.LocalDate;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/user/plan")
public class UserPlanController {

    @Autowired
    private UserPlanService userPlanService;
    //插入计划
    @PostMapping("/add")
    public Map<String, Object> addPlan(@RequestBody UserPlan plan, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        plan.setUserId(userId);
        boolean success = userPlanService.addPlan(plan);
        return Map.of("success", success, "message", success ? "添加成功" : "添加失败");
    }
    //更新计划
    @PutMapping("/update")
    public Map<String, Object> updatePlan(@RequestBody UserPlan plan, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null || !userId.equals(plan.getUserId())) {
            return Map.of("success", false, "message", "权限不足");
        }
        boolean success = userPlanService.updatePlan(plan);
        return Map.of("success", success, "message", success ? "更新成功" : "更新失败");
    }
    //删除计划
    @DeleteMapping("/delete")
public Map<String, Object> deletePlan(
        @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate planTime,
        HttpSession session) {

    Integer userId = (Integer) session.getAttribute("userId");
    if (userId == null) {
        return Map.of("success", false, "message", "未登录");
    }

    boolean success = userPlanService.deletePlan(userId, planTime);
    return Map.of("success", success, "message", success ? "删除成功" : "删除失败");
}
    //根据id查找计划
    @GetMapping("/{id}")
    public Map<String, Object> getPlan(@PathVariable Integer id, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        UserPlan plan = userPlanService.getPlanById(id, userId);
        return plan != null
                ? Map.of("success", true, "data", plan)
                : Map.of("success", false, "message", "计划不存在");
    }
    //列出用户所有计划
    @GetMapping("/list")
    public Map<String, Object> listPlans(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        List<UserPlan> list = userPlanService.getPlansByUserId(userId);
        return Map.of("success", true, "data", list);
    }
}